﻿using KalevaAalto.DataPart.Excel.Base;
using KalevaAalto.DataPart.Excel.Error;
using KalevaAalto.DataPart.Models;
using Spire.Xls;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KalevaAalto.DataPart.Excel.Models
{
    public class WorksheetTableInfo
    {
        private BaseWorksheet _worksheet;
        private int _titleRow = 0;
        private int _serCol = 0;
        private int _rowCount = 0;
        private Dictionary<string,int> _columnDic;



        private void AcquireColumnDictionary()
        {
            int maxColumn = _worksheet.Range.EndPos.Column;
            
            for(int column = 1;column <= maxColumn; column++)
            {
                var cell = _worksheet.Cells[_titleRow, column];
                if(cell is not null && cell.Value is not null)
                {
                    var cellString = cell.Value.GetString();
                    if (!string.IsNullOrEmpty(cellString))
                    {
                        if (_columnDic.ContainsKey(cellString))
                        {
                            throw new WorksheetError(_worksheet, $"字段名称“{cellString}”重复；");
                        }
                        else
                        {
                            _columnDic.Add(cellString, column);
                        }
                    }
                }
            }
            if(_columnDic.Count == 0)
            {
                throw new WorksheetError(_worksheet, @"字段列表为空；");
            }
            _serCol = _columnDic.Min(it => it.Value);
        }


        private void AcquireRowCount(int markColumn)
        {
            int maxRow = _worksheet.Range.EndPos.Row;
            _rowCount = 0;
            for(int row = _titleRow + 1; row <= maxRow; row++)
            {
                var cell = _worksheet.Cells[row, markColumn];
                if(cell is null || cell.Value is null)
                {
                    break;
                }
                else
                {
                    var cellString = cell.Value.GetString();
                    if (string.IsNullOrEmpty(cellString))
                    {
                        break;
                    }
                }
                _rowCount++;
            }
        }


        public WorksheetTableInfo(BaseWorksheet worksheet,string markColumnName) 
        {
            if (string.IsNullOrEmpty(markColumnName))
            {
                throw new WorksheetError(worksheet,@"标记的字段名称不可为空；");
            }
            _worksheet = worksheet;
            var cell = worksheet.Range.Search(cell =>
            {
                var cellString = cell.Value.GetString();
                return cellString == markColumnName;
            });
            if(cell is null)
            {
                throw new WorksheetError(worksheet,$"找不到字段名称“{markColumnName}”；");
            }

            _titleRow = cell.StartPos.Row;
            if(_titleRow <= 0)
            {
                throw new WorksheetError(worksheet, $"找不到字段名称“{markColumnName}”；");
            }

            _columnDic = new Dictionary<string, int>();
            AcquireColumnDictionary();


            AcquireRowCount(cell.StartPos.Column);


        }




        public BaseWorksheet Worksheet => _worksheet;
        public int TitleRow => _titleRow;
        public int ColumnCount => _columnDic.Count;
        public int RowCount => _rowCount;
        public int SummaryRow => TitleRow + RowCount + 1;

        public IDictionary<string, int> Columns => _columnDic;
        public int SerCol => Columns.Min(it => it.Value);
        public int EndCol => Columns.Max(it => it.Value);



        public BaseRange TableWithSummary => Worksheet.Cells[TitleRow, SerCol, SummaryRow, EndCol]!;
        public BaseRange TableWithoutSummary => Worksheet.Cells[TitleRow, SerCol, TitleRow + RowCount, EndCol]!;

        /// <summary>
        /// 字段名称所在单元格区域
        /// </summary>
        public BaseRange ColumnRange => Worksheet.Cells[TitleRow, SerCol, TitleRow, EndCol]!;

        /// <summary>
        /// 合计所在单元格区域
        /// </summary>
        public BaseRange SummaryRange => Worksheet.Cells[SummaryRow, SerCol, SummaryRow, EndCol]!;


        /// <summary>
        /// 数据所在单元格区域
        /// </summary>
        public BaseRange DataRange => Worksheet.Cells[TitleRow + 1, SerCol, TitleRow + RowCount, EndCol]!;

        public BaseRange DataRangeOfColumn(string columnName)
        {
            if (!Columns.ContainsKey(columnName))
            {
                throw new WorksheetError(Worksheet, $"找不到字段名称“{columnName}”；");
            }
            if(RowCount <= 0)
            {
                throw new WorksheetError(Worksheet, @"工作表记录数量为零；");
            }
            int column = Columns[columnName];
            var rng = Worksheet.Cells[TitleRow + 1, column, TitleRow + RowCount, column]!;
            return rng;
        }


        public BaseRange SummaryCellOfColumn(string columnName)
        {
            if (!Columns.ContainsKey(columnName))
            {
                throw new WorksheetError(Worksheet, $"找不到字段名称“{columnName}”；");
            }
            int column = Columns[columnName];
            var cell = Worksheet.Cells[SummaryRow , column]!;
            return cell;
        }



        private void ChangeEntireWorksheet()
        {
            var rng = Worksheet.Cells;
            rng.Style.Fill.BackgroundColor = Color.White;
            rng.Style.Font.Name = @"宋体";
            rng.Style.Font.Color = Color.Black;
            rng.Style.Fill.BackgroundColor = Color.White;
            rng.Style.VerticalAlignment = DataPart.Enums.VerticalAlignment.Center;

            Worksheet.View.ShowGridLines = false;

        }


        private void ChangeEntireTable()
        {
            var rng = TableWithSummary;
            rng.Style.HorizontalAlignment = DataPart.Enums.HorizontalAlignment.Center;
            rng.Style.WrapText = false;
            rng.Style.Font.Size = 9;
            rng.Style.Font.Weight = DataPart.Enums.FontWeight.Thin;
            rng.Style.Border.Top = DataPart.Enums.BorderStyle.Thin;
            rng.Style.Border.Bottom = DataPart.Enums.BorderStyle.Thin;
            rng.Style.Border.Left = DataPart.Enums.BorderStyle.Thin;
            rng.Style.Border.Right = DataPart.Enums.BorderStyle.Thin;
        }


        private void ChangeTitleRow()
        {
            var rng = ColumnRange;
            rng.Style.WrapText = true;
            rng.Style.Font.Size = 10;
            rng.Style.Font.Weight = DataPart.Enums.FontWeight.Bold;
            rng.Style.Font.Name = @"黑体";
        }


        private void ChangeSummaryRow()
        {
            var rng = SummaryRange;
            rng.Style.Font.Size = 10;
            rng.Style.Font.Weight = DataPart.Enums.FontWeight.Bold;
            rng.Style.Font.Name = @"黑体";
        }


        public void InitStyle()
        {
            ChangeEntireWorksheet();
            ChangeEntireTable();
            ChangeTitleRow();
            ChangeSummaryRow();
        }


        public void ChangeDataColumnFormat(string columnName,Action<IStyle> changeStyle)
        {
            var rng = DataRangeOfColumn(columnName);
            changeStyle(rng.Style);
        }




        public BaseRange GetCell(string columnName,int n)
        {
            if (!Columns.ContainsKey(columnName))
            {
                throw new WorksheetError(Worksheet, $"找不到字段名称“{columnName}”；");
            }
            if (n > RowCount)
            {
                throw new WorksheetError(Worksheet, $"工作表的最大记录个数为{RowCount}；");
            }
            var column = Columns[columnName];
            var cell = Worksheet.Cells[TitleRow + n, column]!;
            return cell;
        }

        public object? GetValue(string columnName, int n)
        {
            var cell = GetCell(columnName, n);
            var obj = cell.Value;
            return obj;
        }











    }
}
